import { doLogout } from '@/api/user'
import Vue from 'vue'
import router from '@/router'
export default {
  state: {
    isLogin: false,
    userInfo: {},
    menu: [],
    cached: [],
    // excludeCache: [],
    defaultActive: '',
  },
  getters: {
    userMenu(state) {
      return state.menu
    },
    userInfo(state) {
      return state.userInfo
    },
    getTags(state) {
      return state.cached
    },
    // getExcludeCache(state) {
    //   return state.excludeCache
    // },
    getDefaultActive(state) {
      return state.defaultActive
    },
  },
  mutations: {
    changeLogin(state, isLogin) {
      state.isLogin = isLogin
    },
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setMenu(state, menu) {
      state.menu = menu
    },
    addCache(state, tag) {
      if (state.cached.some((ele) => ele.name === tag.name)) return
      state.cached.push(tag)
    },
    removeCache(state, tag) {
      let index = state.cached.findIndex((ele) => ele.name === tag.name)
      if (index !== -1) {
        state.cached.splice(index, 1)
        if (state.cached.length === 0) {
          return router.push('/dashboard')
        }
        // 关闭掉的不是自己
        if (router.currentRoute.name !== tag.name) return
        // 接着路由导向到前一个或者后一个
        let nextTag = state.cached[index - 1] || state.cached[index]
        nextTag && router.push(nextTag)
        // // 添加排除名单
        // state.excludeCache.push(tag.name)
        // // 下一个更新清空排除的tag
        // Vue.nextTick(() => {
        //   state.excludeCache.length = 0
        // })
        // // 立刻销毁组件
        // history.back()
      }
      // let index = state.cached.findIndex(ele => ele.name === tag.name)
      // if (index !== -1) {
      //     state.cached.splice(index, 1);
      // }
    },
    changeDefaultActive(state, path) {
      state.defaultActive = path
    },
    cleanTags(state) {
      state.cached.length = 0
    },
  },
  actions: {
    async doLogoutVx({ commit }) {
      // 发请求
      await doLogout()
      // 清空需要的资源
      window.sessionStorage.removeItem('token') // 没有办法进入页面，跳转到登录
      commit('setMenu', []) // 再次进入路由需要调用loadMenu
      commit('changeUserInfo', null)
      commit('changeLogin', false)
      commit('cleanTags')
      // 跳转
    },
  },
}
